<template>
  <div class="disease-list-page">
    <cp-nav-bar title="疾病百科" />

    <!-- 搜索框 -->
    <div class="search-bar">
      <van-search
        v-model="searchText"
        shape="round"
        placeholder="搜索疾病名称、症状"
        @search="onSearch"
      />
    </div>

    <!-- 筛选条件 -->
    <div class="filter-bar">
      <van-dropdown-menu>
        <van-dropdown-item
          v-model="currentDepartment"
          :options="departmentOptions"
          @change="onFilterChange"
        />
        <van-dropdown-item
          v-model="currentSpecialZone"
          :options="specialZoneOptions"
          @change="onFilterChange"
        />
        <van-dropdown-item
          v-model="currentSort"
          :options="sortOptions"
          @change="onFilterChange"
        />
      </van-dropdown-menu>
    </div>

    <!-- 疾病列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        :error="error"
        error-text="请求失败，点击重试"
        finished-text="没有更多了"
        @load="loadDiseaseList"
      >
        <div class="disease-list">
          <template v-if="!error">
            <div
              class="disease-card"
              v-for="disease in diseases"
              :key="disease.id"
              @click="onViewDetail(disease)"
            >
              <div class="disease-info">
                <img
                  :src="getDiseaseImage(disease.image_name)"
                  class="disease-image"
                  @error="onImageError"
                />
                <div class="info-right">
                  <div class="top-line">
                    <span class="name">{{ disease.name }}</span>
                    <span
                      class="special-tag"
                      v-if="disease.is_special_zone === '是'"
                    >
                      专科
                    </span>
                  </div>
                  <div class="english-name" v-if="disease.english_name">
                    {{ disease.english_name }}
                  </div>
                  <div class="summary">
                    {{ disease.summary || '暂无疾病简介' }}
                  </div>
                  <!-- 科室标签 -->
                  <div
                    class="departments"
                    v-if="disease.departments && disease.departments.length"
                  >
                    <span class="dept-label">相关科室：</span>
                    <span
                      class="dept-tag"
                      v-for="dept in disease.departments"
                      :key="dept.id"
                    >
                      {{ dept.name }}
                    </span>
                  </div>
                  <div class="symptoms" v-if="disease.symptoms">
                    <span class="label">主要症状：</span>
                    {{ disease.symptoms }}
                  </div>
                </div>
              </div>
            </div>
          </template>
          <!-- 骨架屏 -->
          <template v-if="loading && !diseases.length">
            <div class="disease-card" v-for="i in 3" :key="i">
              <van-skeleton title avatar :row="3" />
            </div>
          </template>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import type { Disease, Department } from '@/types/disease'
import { getDiseaseList } from '@/services/disease'
import { showToast } from 'vant'
import { request } from '@/utils/request'

const router = useRouter()
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const error = ref(false)
const searchText = ref('')

const departmentOptions = ref([{ text: '全部科室', value: '' }])
const currentDepartment = ref('')

const specialZoneOptions = ref([
  { text: '全部疾病', value: '' },
  { text: '专科疾病', value: '是' },
  { text: '普通疾病', value: '否' }
])
const currentSpecialZone = ref('')

const sortOptions = ref([
  { text: '默认排序', value: '' },
  { text: '按名称升序', value: 'name_asc' },
  { text: '按名称降序', value: 'name_desc' },
  { text: '按更新时间', value: 'update_time_desc' }
])
const currentSort = ref('')

// 分页数据
const pageSize = 10
const pageNum = ref(1)
const diseases = ref<Disease[]>([])

// 加载科室列表
const loadDepartmentList = async () => {
  try {
    const res = await request.get('/consult/dep/all')
    const list = res.data
    departmentOptions.value = list.map((item: Department) => ({
      text: item.name,
      value: item.id.toString()
    }))
    departmentOptions.value.unshift({ text: '全部科室', value: '' })
  } catch (e) {
    console.error('加载科室列表失败:', e)
  }
}

onMounted(() => {
  loadDepartmentList()
  loadDiseaseList()
})

// 获取疾病列表
const loadDiseaseList = async (isRefresh = false) => {
  // 如果是刷新，重置状态
  if (isRefresh) {
    pageNum.value = 1
    diseases.value = []
    error.value = false
    finished.value = false
  }

  try {
    loading.value = true

    // 解析排序参数
    let sortBy = ''
    let sortOrder = ''
    if (currentSort.value) {
      const parts = currentSort.value.split('_')
      if (parts.length === 2) {
        sortBy = parts[0]
        sortOrder = parts[1]
      }
    }

    const res = await getDiseaseList({
      pageSize,
      pageNum: pageNum.value,
      keyword: searchText.value,
      departmentId: currentDepartment.value
        ? parseInt(currentDepartment.value)
        : undefined,
      isSpecialZone: currentSpecialZone.value as '是' | '否' | '',
      sortBy,
      sortOrder: sortOrder as 'asc' | 'desc' | ''
    })

    console.log('疾病列表查询参数:', {
      pageSize,
      pageNum: pageNum.value,
      keyword: searchText.value,
      departmentId: currentDepartment.value
        ? parseInt(currentDepartment.value)
        : undefined,
      isSpecialZone: currentSpecialZone.value,
      sortBy,
      sortOrder
    })
    console.log('疾病列表API响应:', res)

    if (res.data && res.data.length) {
      diseases.value.push(...res.data)
      pageNum.value++

      // 如果返回的数据少于pageSize，说明没有更多数据了
      if (res.data.length < pageSize) {
        finished.value = true
      }
    } else {
      finished.value = true
      if (!res.data) {
        throw new Error('获取疾病列表失败')
      }
    }
    error.value = false
  } catch (e) {
    error.value = true
    showToast('获取疾病列表失败')
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true
  loadDiseaseList(true)
}

// 搜索
const onSearch = () => {
  loadDiseaseList(true)
}

// 筛选条件变化
const onFilterChange = () => {
  nextTick(() => {
    loadDiseaseList(true)
  })
}

// 查看详情
const onViewDetail = (disease: Disease) => {
  router.push(`/disease/${disease.id}`)
}

// 获取疾病图片
const getDiseaseImage = (imageName?: string) => {
  if (imageName) {
    return `${import.meta.env.VITE_APP_API_BASE_URL}/public/images/${imageName}`
  }
  return '/src/assets/ad.png' // 默认图片
}

// 图片加载失败处理
const onImageError = (event: Event) => {
  const target = event.target as HTMLImageElement
  target.src = '/src/assets/ad.png'
}
</script>

<style lang="scss" scoped>
.disease-list-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-bar {
  background: #fff;
  padding: 10px 15px;
  .van-search {
    padding: 0;
    background: transparent;
  }
}

.filter-bar {
  position: sticky;
  top: 0;
  z-index: 100;
  background: #fff;
  border-bottom: 1px solid #f5f5f5;
}

.disease-list {
  padding: 10px 15px;
  .disease-card {
    background: #fff;
    border-radius: 8px;
    padding: 12px;
    margin-bottom: 10px;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .disease-info {
      display: flex;
      .disease-image {
        width: 60px;
        height: 60px;
        border-radius: 8px;
        margin-right: 12px;
        object-fit: cover;
        flex-shrink: 0;
        background-color: #f5f5f5;
      }

      .info-right {
        flex: 1;
        min-width: 0;
        .top-line {
          display: flex;
          align-items: center;
          margin-bottom: 5px;
          .name {
            font-size: 16px;
            font-weight: bold;
            margin-right: 8px;
            color: #121826;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            flex: 1;
            min-width: 0;
          }
          .special-tag {
            background: #ff6b35;
            color: #fff;
            font-size: 10px;
            padding: 2px 6px;
            border-radius: 10px;
            white-space: nowrap;
            flex-shrink: 0;
          }
        }

        .english-name {
          color: #6f6f6f;
          font-size: 12px;
          margin-bottom: 5px;
          font-style: italic;
        }

        .summary {
          color: #333;
          font-size: 13px;
          margin-bottom: 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          line-clamp: 2;
          -webkit-box-orient: vertical;
          line-height: 18px;
          height: 36px;
        }

        .symptoms {
          color: #666;
          font-size: 12px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          line-clamp: 1;
          -webkit-box-orient: vertical;

          .label {
            color: #16c2a3;
            font-weight: 500;
          }
        }

        .departments {
          margin-bottom: 8px;
          font-size: 12px;
          line-height: 18px;

          .dept-label {
            color: #16c2a3;
            font-weight: 500;
          }

          .dept-tag {
            background: linear-gradient(135deg, #16c2a3, #13b394);
            color: #fff;
            font-size: 10px;
            padding: 2px 6px;
            border-radius: 8px;
            margin-right: 4px;
            white-space: nowrap;
          }
        }
      }
    }
  }
}
</style>
